#include<iostream>
#include<queue>
#include<string>
#include<fstream>
#include<sstream>
#include<vector>
#include<list>
#include<assert.h>
using namespace std;
string g_path = "./info.txt";

typedef class Process
{
public:
	string _process_name;
	int _arrive_time; // 到达时间
	int _server_time; // 服务时间

	int _finsh_time;// 完成时间
	bool _isok = false; // 是否被服务过


	Process(string& process_name, int arrive_time, int server_time)
		:_process_name(process_name), _arrive_time(arrive_time), _server_time(server_time)
	{}
	Process() {}
}PCB;

auto cmp_arrive_time = [](const Process& p1, const Process& p2) { return p1._arrive_time < p2._arrive_time; };
auto cmp_server_time = [](const Process& p1, const Process& p2) { return p1._server_time > p2._server_time; }; // 小堆

list<Process> ready_queue;
priority_queue<Process, vector<Process>, decltype(cmp_server_time)> pq(cmp_server_time);
vector<Process> v; // 保存进程信息

void Read(string file_path = g_path)
{
	ifstream file(g_path);
	if (!file.is_open())
	{
		cout << "打开文件失败" << endl;
	}

	string header;
	getline(file, header); // 丢弃第一行
	//cout << header.c_str() << endl;
	string line;
	cout << "进程名" << "\t" << "到达时间" << "\t" << "服务时间" << endl;
	while (getline(file, line))
	{
		istringstream iss(line); // 需要 sstream头文件
		Process p;
		iss >> p._process_name >> p._arrive_time >> p._server_time;

		cout << p._process_name << "\t" << p._arrive_time << "\t\t" << p._server_time << endl;
		v.push_back(p);
	}
	sort(v.begin(), v.end(), cmp_arrive_time);
	cout << "============================" << endl;
}

// 先服务到达 且 服务时间最短的进程
void Schedule()
{
	int current_time = 0; // 当前时间
	int finsh_time = -1;
	int index = 0;

	ready_queue.push_back(v[index]); 
	current_time = v[index]._arrive_time;
	while (true)
	{
		
		auto front = ready_queue.front(); // ？

		front._finsh_time = current_time + front._server_time;

		assert(!ready_queue.empty()); // 值为假停止运行
		ready_queue.pop_front(); // 上处理机

		cout << front._process_name << " get cpu" << endl;

		front._isok = true;
		
		while (current_time <= front._finsh_time) // 非抢占式
		{
			current_time++;
			cout << front._process_name << " is runing..." << endl;
			
		}
		cout << front._process_name << "finsh_time:" << front._finsh_time << endl;
		for (int i = index + 1; i < v.size(); i++)
		{
			if (v[i]._isok == false && current_time <= v[i]._arrive_time)
			{
				pq.push(v[i]);
				cout << v[i]._process_name << " join ready_queue" << endl;
			}
			while (!pq.empty()) 
			{
				auto top = pq.top();
				pq.pop();
				ready_queue.push_back(top);
			}
		}
		bool end = true;
		for (auto it : v)
		{
			if (it._isok == false)
			{
				end = false;
			}
		}
		if (end)
		{
			break;
		}
		
		current_time++;
		
	}
}

int main()
{

	cout << "开始从文件中读取信息" << endl;
	Read();
	Schedule();
	




	return 0;
}